package com.feiyu.auth.util;

import com.feiyu.auth.entity.AuthInfo;
import com.feiyu.common.constant.TokenConstant;
import com.feiyu.user.entity.User;
import com.feiyu.user.entity.UserInfo;
import org.springblade.core.tool.utils.Func;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tang ming
 * @since 2021/11/28 15:05
 */
public class TokenUtil {

    public final static String CAPTCHA_HEADER_KEY = "Captcha-Key";
    public final static String CAPTCHA_HEADER_CODE = "Captcha-Code";
    public final static String CAPTCHA_NOT_CORRECT = "验证码不正确";
    public final static String TENANT_HEADER_KEY = "Tenant-Id";
    public final static String DEFAULT_TENANT_ID = "000000";
    public final static String USER_TYPE_HEADER_KEY = "User-Type";
    public final static String DEFAULT_USER_TYPE = "web";
    public final static String USER_NOT_FOUND = "用户名或密码错误";
    public final static String HEADER_KEY = "Authorization";
    public final static String HEADER_PREFIX = "Basic ";
    public final static String DEFAULT_AVATAR = "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";

    /**
     * 创建认证token
     * @return token
     */
    public static AuthInfo createAuthInfo(UserInfo user) {

        //设置jwt参数
        Map<String, String> param = new HashMap<>(16);
        param.put(TokenConstant.TOKEN_TYPE, TokenConstant.ACCESS_TOKEN);
        param.put(TokenConstant.OAUTH_ID, user.getOauthId());
        param.put(TokenConstant.USER_ID, Func.toStr(user.getId()));
        param.put(TokenConstant.ROLE_ID, Func.toStr(user.getRoleId()));
        param.put(TokenConstant.ACCOUNT, user.getAccount());
        param.put(TokenConstant.USER_NAME, user.getName());
        param.put(TokenConstant.ROLE_NAME, user.getRoles());

        TokenInfo accessToken = SecureUtil.createJWT(param, "audience", "issuser");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setUserId(user.getId());
        authInfo.setOauthId(user.getOauthId());
        authInfo.setAccount(user.getAccount());
        authInfo.setUserName(user.getName());
        authInfo.setAvatar(user.getAvatar());
        authInfo.setAuthority(user.getRoles());
        authInfo.setAccessToken(accessToken.getToken());
        authInfo.setExpiresIn(accessToken.getExpire());
        authInfo.setRefreshToken(createRefreshToken(user).getToken());
        authInfo.setTokenType(TokenConstant.BEARER);
        authInfo.setLicense(TokenConstant.LICENSE_NAME);
        return authInfo;
    }

    /**
     * 创建refreshToken
     *
     * @param user 用户信息
     * @return refreshToken
     */
    private static TokenInfo createRefreshToken(UserInfo user) {

        Map<String, String> param = new HashMap<>(16);
        param.put(TokenConstant.TOKEN_TYPE, TokenConstant.REFRESH_TOKEN);
        param.put(TokenConstant.USER_ID, Func.toStr(user.getId()));
        return SecureUtil.createJWT(param, "audience", "issuser");
    }

}
